# -*- coding: utf-8 -*- 
import tornado.web
import time
from common import BaseHandler
from pymongo.objectid import ObjectId as _id
from BeautifulSoup import BeautifulSoup

cached_forums = {
    'public':{  
        'name': u'广场',
        'cats':[{'id':'1','name':u'调研问答'},
                {'id':'2','name':u'经验分享'},
                {'id':'3','name':u'金融大杂烩'},
                {'id':'4','name':u'站务/建议'}, ]
    }
}

def latest_threads(db,count=10): 
    cursor = db.threads.find({'title':1,'created_at':1,'uid':1}).sort('created_at',-1).limit(count)
        

class ForumBaseHandler(BaseHandler):
    def user_other_threads(self,uid,tid,count=11):
        threads = []
        cursor = self.db.threads.find({'uid':uid},{'title':1,'created_at':1}).sort('created_at',-1).limit(count)
        tid = _id(tid)
        for thread in cursor:
            if thread['_id']==tid: continue
            threads.append(thread)
        return threads
            

class ForumHandler(ForumBaseHandler):  
    #@tornado.web.authenticated
    def get(self): 
        fid = self.get_argument('fid','public') #forum id,default to public
        cid = self.get_argument('cid',None) #category id
        sid = self.get_argument('sid',None) #status id/special
        start = self.get_argument('idx',0)  #start of forum threads to pull/for paging
        count = self.get_argument('cnt',20) #count of forum threads to pull/for paging

        forum = cached_forums[fid]
        filter = {}
        if cid: filter['category'] = cid
        threads = [] 
        for thread in self.db.threads.find(filter,{'content':0}).sort('created_at',-1).skip(start).limit(count):
            threads.append(thread)
            
        for thread in threads: #popup cached whole user info
            thread['user'] = self.user(thread['uid'])
                
        self.render('forum/forum.html',threads=threads,forum=forum,current_cat=cid)
 
class ThreadHandler(ForumBaseHandler):   
    def get(self,tid):  
        forum = cached_forums['public']
        thread = self.db.threads.find_one({'_id':_id(tid)}) 
        if thread is None:
            self.write('not found')
            return
        uid = thread['uid']
        thread['user'] = self.user(uid)
        others = self.user_other_threads(uid, tid) 
        self.render('forum/thread.html',thread=thread,others=others,forum=forum) 
        
class PostHandler(ForumBaseHandler):  
    def get(self):  
        self.render('forum/post.html')
    
    def to_summary(self,text,count = 100):
        soup = BeautifulSoup(text)
        pageText = soup.findAll(text=True)
        res = "" 
        for text in pageText:  
            res += text.replace('&nbsp;', '')
            if len(res)>count: break
        return res[0:count]
    
    def post(self):
        title = self.get_argument('title')
        category = self.get_argument('category')
        content = self.get_argument('content')
        tags = self.get_argument('tags','')
        summary = self.to_summary(content)
        
        user = self.get_current_user()
        entry = {
            'uid': user['uid'], 
            'title': title,            
            'content': content, 
            'summary': summary,
            'category': category,
            'tags': tags.split(),
            'created_at': time.time()
        }
        self.db.threads.save(entry);
        
        self.write({'success': 1, 'id':str(entry['_id'])})

handlers = [
    ('/forum/thread/([^/]*)', ThreadHandler), 
    ('/forum/post', PostHandler), 
    ('/forum', ForumHandler),
]  